package com.peza.bikelog.common.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileProcessor {

	
	private static FileProcessor instance;
	
	private FileProcessor(){
		
	}
	
	public static FileProcessor getInstance(){
		if (instance == null){
			instance = new FileProcessor();
		}
		return instance;
	}
	
	public File getFile(String path){
		File file = new File(path);
		return file;
	}
	
	public List<File> getFiles (String path, String extension){
		File inDir = new File(path);
		File[] fileArray = inDir.listFiles();
		List <File> files = new ArrayList<File>();
		for (File file : fileArray) {
			if (file.getName().endsWith(extension)) {
				files.add(file);
			}
		}
		return files;
	}
	
	public String writeFile(String contents, String path, String filename, String extension){
		String name = null;
		FileWriter writer = null;
		File file = null;
		boolean written = false;
		int seq = 1;
		while (!written){
			name = filename+seq+"-exported"+extension;
			file = new File(path+name);
			if (!file.exists()){
				try {
					writer = new FileWriter(file);
					writer.write(contents);
					writer.flush();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					written = true;
					try {
						writer.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			} else {
				seq++;
			}

		}
		return name;
	}
	
}
